package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.article.service.IApArticleFreemarkerService;
import com.heima.article.service.IApArticleService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional //开启事务
public class ApArticleFreemarkerServiceImpl implements IApArticleFreemarkerService {
    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IApArticleService apArticleService;
    /**
     * 生成静态页面并保存到到minio中
     * @param apArticle
     * @param content
     */
    @Override
    @Async //异步调用,此方法
    public void createArticleToMinio(ApArticle apArticle, String content) {
        //校验请求参数中的文章内容是否为空
        if (StringUtils.isNotBlank(content)){
            //不为空,则合成静态文件内容,先获取文章模板对象
            Template template = null;
            StringWriter stringWriter = new StringWriter();
            try {
                template = configuration.getTemplate("article.ftl");
                //文章数据为字符串类型,有很多个段落,需要将其解析成jason格式的数组
                JSONArray data = JSONArray.parseArray(content);
                //合成静态资源时,和模板进行合成的数据只能是map类型的,需要将数据存储到map中
                Map<String,Object> map = new HashMap<>();
                map.put("content",data);
                //合成
                template.process(map, stringWriter);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //将html静态内容上传到minio中
            InputStream inputStream = new ByteArrayInputStream(stringWriter.toString().getBytes());
            //获取文章id,生成文件名称
            String filename = apArticle.getId().toString()+".html";
            //调用minio工具类的上传文件方法,将文件上传
            String path = fileStorageService.uploadHtmlFile("", filename, inputStream);
            //修改数据库中apArticle的static_url的值
            apArticle.setStaticUrl(path);
            apArticleService.updateById(apArticle);
        }
    }
}
